﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;


namespace Lumberjack.BusinessLogic
{
    public class RepositoryService<TEntity> : IRepository<TEntity> where TEntity : class
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private DbContext _dbContext;

        private IDbSet<TEntity> Entities
        {
            get { return this._dbContext.Set<TEntity>(); }
        }

        public RepositoryService(DbContext context)
        {
            _dbContext = context;
        }


        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (this._dbContext != null)
                {
                    this._dbContext.Dispose();
                    this._dbContext = null;
                }
            }
        }

        IQueryable<TEntity> IRepository<TEntity>.GetAll()
        {
            return Entities.AsQueryable();
        }

        TEntity IRepository<TEntity>.GetById(object id)
        {
            return Entities.Find(id);
        }

        void IRepository<TEntity>.Insert(TEntity entity)
        {
            Entities.Add(entity);
            this._dbContext.SaveChanges();
        }

        void IRepository<TEntity>.Update(TEntity entity)
        {
            _dbContext.Entry(entity).State = System.Data.EntityState.Modified;
            _dbContext.SaveChanges();
        }

        void IRepository<TEntity>.Delete(TEntity entity)
        {
            Entities.Remove(entity);
            _dbContext.SaveChanges();
        }
    }
}
